package com.neu.service;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neu.common.JwtTokenUtils;
import com.neu.dao.AdminDao;
import com.neu.dao.AuditDao;
import com.neu.entity.Admin;
import com.neu.entity.Audit;
import com.neu.entity.Params;
import com.neu.exception.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class AuditService {
    @Autowired
    private AuditDao auditDao;
    @Autowired
    private AdminDao adminDao;

    public void add(Audit audit) {
        auditDao.insertSelective(audit);
    }

    public void update(Audit audit) {
        auditDao.updateByPrimaryKeySelective(audit);
    }

    public PageInfo<Audit> findBySearch(Params params) {

        Admin user = JwtTokenUtils.getCurrentUser();
        if(ObjectUtil.isNull(user)){
            throw new CustomException("从token中未解析到用户信息，请重新登录");
        }
        if("ROLE_STUDENT".equals(user.getRole())){
            params.setUserId(user.getId());
        }
        //开启分页查询
        PageHelper.startPage(params.getPageNum(),params.getPageSize());
        //接下来的查询会自动按照当前开启的分页设置来查询
        List<Audit> list = auditDao.findBySearch(params);

//        for(Audit audit:list){
//            if(ObjectUtil.isNotEmpty(audit.getUserId())){
//                Admin user = adminDao.selectByPrimaryKey(audit.getUserId());
//                if(ObjectUtil.isNotEmpty(user)){
//                    audit.setUserName(user.getName());
//                }
//            }
//
//
//        }
        return PageInfo.of(list);
    }

    public void delete(Integer id) {
        auditDao.deleteByPrimaryKey(id);
    }


}
